#coding=utf-8
__author__ = 'ezhenyz'

#from django.template import loader, Context
#from django.http import HttpResponse
#
#def index(request):
#    tpl = loader.get_template("index.html")
#    ctx = Context()
#    return HttpResponse(tpl.render(ctx))

from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
import os,ImageFile,uuid
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt

def index(request):
    ctx=dict()

    if request.method=="POST":
        file = request.FILES.get("Filedata",None)
        if _upload(file):
            ctx["message"]="上传成功！"
        else:
            ctx["message"]="上传出错！"
    return render_to_response("index.html",ctx,RequestContext(request))

@csrf_exempt
def uploadify_script(request):
    response=HttpResponse()
    response['Content-Type']="text/javascript"
    ret="0"
    file = request.FILES.get("Filedata",None)
    if file:
        if _upload(file):
            ret="1"
        ret="2"
    response.write(ret)
    return response

def _upload(file):
    '''图片上传函数'''
    if file:
        path=os.path.join(settings.MEDIA_ROOT,'Cartoon/preview/')
        file_name=str(uuid.uuid1())+".jpg"
        path_file=os.path.join(path,file_name)
        parser = ImageFile.Parser()
        for chunk in file.chunks():
            parser.feed(chunk)
        img = parser.close()
        try:
            if img.mode != "RGB":
                img = img.convert("RGB")
            img.save(path_file, 'jpeg',quality=100)
        except:
            return False
        return True
    return False